package com.fitzone.web.controller.admin;

import com.fitzone.common.exception.LoginFailedException;
import com.fitzone.common.utils.JwtUtil;
import com.fitzone.common.utils.MD5Util;
import com.fitzone.common.result.Result;
import com.fitzone.common.result.ResultCodeEnum;
import com.fitzone.model.entity.SysUser;
import com.fitzone.model.vo.LoginVo;
import com.fitzone.web.service.SysUserService;
import com.fitzone.web.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 后台登录登出
 * </p>
 */
@Api(tags = "后台登录管理")
@RequiredArgsConstructor
@RestController("adminAuthController")
@RequestMapping("/admin/system/auth")
public class AuthController {

    private final SysUserService sysUserService;

    private final UserService userService;

    /**
     * 登录
     */
    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo) {
        // 已闲置，被TokenLoginFilter替代了
        SysUser sysUser = sysUserService.getByUsername(loginVo.getUsername());
        if(null == sysUser) {
            throw new LoginFailedException(ResultCodeEnum.ACCOUNT_ERROR);
        }
        if(!MD5Util.encrypt(loginVo.getPassword()).equals(sysUser.getPassword())) {
            throw new LoginFailedException(ResultCodeEnum.PASSWORD_ERROR);
        }
        if(sysUser.getStatus().intValue() == 0) {
            throw new LoginFailedException(ResultCodeEnum.ACCOUNT_STOP);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("token", JwtUtil.createToken(sysUser.getId(), sysUser.getUsername()));
        return Result.ok(map);
    }

    /**
     * 获取用户信息
     */
    @ApiOperation(value = "获取用户信息")
    @GetMapping("/info")
    public Result info(HttpServletRequest request) {
        String username = JwtUtil.getUsername(request.getHeader("token"));
        Map<String, Object> map = sysUserService.getUserInfo(username);
        return Result.ok(map);
    }

    /**
     * 退出
     */
    @ApiOperation(value = "退出")
    @PostMapping("/logout")
    public Result logout(){
        return Result.ok();
    }

    @GetMapping("/qrcode")
    public Result getQrcode(){
        return Result.ok(userService.getQrcode());
    }
}
